package com.yunji.framework_template.web.controller;

import java.io.IOException;
import java.util.Collections;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.HttpException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.yunji.framework_template.biz.cache.CacheService;
import com.yunji.framework_template.biz.service.GameService;
import com.yunji.framework_template.common.util.ListUtil;
import com.yunji.framework_template.common.util.NumberUtil;
import com.yunji.framework_template.common.web.Page;
import com.yunji.framework_template.common.web.Result;
import com.yunji.framework_template.orm.persistence.model.Game;
import lombok.extern.slf4j.Slf4j;

/**
 * Created by fenglibin on 2018/12/12.
 */
@Slf4j
@Controller
@RequestMapping("/game/")
public class GameController {

    @Value("#{settings['system.domain']}")
    private String       systemDomain;
    @Value("#{settings['http.protocol']}")
    private String      httpProtocol;

    @Autowired
    private GameService  gameService;
    @Resource
    private CacheService cacheService;

    @RequestMapping("selectAll")
    @ResponseBody
    public Result<List<Game>> selectAll() {
        return Result.success(gameService.selectAll());
    }

    @RequestMapping("select")
    @ResponseBody
    public Result<Game> selectByPrimaryKey(Integer id) {
        return Result.success(gameService.selectByPrimaryKey(id));
    }

    @RequestMapping("selectByCondition")
    @ResponseBody
    public Result<List<Game>> selectByCondition(Game record) {
        return Result.success(gameService.selectByCondition(record));
    }

    @RequestMapping("count")
    @ResponseBody
    public Result<Integer> count(Game record) {
        return Result.success(gameService.count(record));
    }

    @RequestMapping("insert")
    @ResponseBody
    public Result<Integer> insertSelective(Game record) {
        return Result.success(gameService.insertSelective(record));
    }

    @RequestMapping("update")
    @ResponseBody
    public Result<Integer> updateByPrimaryKeySelective(Game record) {
        return Result.success(gameService.updateByPrimaryKeySelective(record));
    }

    @RequestMapping("selectByPage")
    @ResponseBody
    public Result<Page<List<Game>>> selectByPage(Page<Game> page) {
        List<Game> list = null;
        page = page.sequentialDisplayCalculate(gameService.count(page.getObj()));
        if (page.getTotalCount() > 0) {
            list = gameService.selectByPage(page);
        }
        Page<List<Game>> result = new Page<List<Game>>(page, list);
        return Result.success(result);
    }

    @RequestMapping("deleteByCondition1")
    @ResponseBody
    public Result<Integer> deleteByCondition(Game record) {
        return Result.success(gameService.deleteByCondition(record));
    }

    @RequestMapping("delete1")
    @ResponseBody
    public Result<Integer> deleteByPrimaryKey(Integer id) {
        return Result.success(gameService.deleteByPrimaryKey(id));
    }

    @RequestMapping("initGames")
    @ResponseBody
    public Result<?> initGames() {
        cacheService.initGames();
        return Result.success(null);
    }

    /**
     * Home page
     */
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public ModelAndView index(HttpServletRequest request, HttpServletResponse response) throws HttpException,
                                                                                        IOException {
        log.info("Game index is accessed.");
        ModelAndView view = new ModelAndView("game/game_index");
        view.getModelMap().addAttribute("indexType", "Game");
        view.getModelMap().addAttribute("systemDomain", systemDomain);
        List<Game> gameList = cacheService.getCountryCache().getPageGame().get(1);
        if(gameList!=null) {
            gameList = ListUtil.randomSort(gameList);
        }
        view.getModelMap().addAttribute("gameList", gameList);
        return view;
    }

    /**
     * Detail page
     */
    @RequestMapping(value = "/detail/{gameId}", method = RequestMethod.GET)
    public ModelAndView detail(@PathVariable("gameId") String gameId) throws HttpException, IOException {
        log.info("Detail access gameId is:" + gameId);
        if (!NumberUtil.isNumber(gameId)) {
            log.warn("The gameId is not number:" + gameId);
            return new ModelAndView("404");
        }
        int nid = Integer.parseInt(gameId);
        Game game = gameService.selectByPrimaryKey(nid);
        if (game == null) {
            log.warn("Cannot get game by gameId:" + gameId);
            return new ModelAndView("404");
        }

        ModelAndView view = new ModelAndView("game/game_detail");
        view.getModelMap().addAttribute("systemDomain", systemDomain);
        view.getModelMap().addAttribute("httpProtocol", httpProtocol);
        // 当前游戏
        view.getModelMap().put("game", game);
        // 推荐的游戏
        view.getModelMap().put("gameList", gameService.getRandomGames());
        // 增加查看次数
        gameService.updateTimesByPrimaryKey(game);
        game.setTimes(game.getTimes()+1);
        cacheService.getCountryCache().getGames().put(game.getId(), game);
        return view;
    }
}
